<?php
/**
 * Created by PhpStorm.
 * User: serenehaly
 * Date: 2018/3/1
 * Time: 17:26
 */

namespace app\api\controller\v1;

use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address
{
    public function createOrUpdateAddress() {
        $validate = new \app\api\validate\Address();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if ($user) {
            $data = $validate->getDataByRule(input('post.'));
            $userAddress = $user->address;
            if ($userAddress) {
                $user->address->save($data);
                return json(new SuccessMessage([
                    'msg' => '收货地址更新成功'
                ]), 201);

                /*throw new SuccessMessage([
                    'msg' => '收货地址更新成功'
                ]);*/
            } else {
                $user->address()->save($data);
                /*return json(new SuccessMessage([
                    'msg' => '收货地址添加成功'
                ]), 201);*/
                throw new SuccessMessage([
                    'msg' => '收货地址添加成功'
                ]);
            }
        } else {
            throw new UserException([
                'code' => 404,
                'msg' => '用户收获地址不存在',
                'errorCode' => 60001
            ]);
        }

    }
}